package com.bike.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bike.entity.HhAgent;
import com.bike.entity.HhPayRecord;
import com.bike.entity.HhWithdraw;
import com.bike.entity.HhWithdrawAgent;
import com.bike.mapper.HhAgentMapper;
import com.bike.mapper.HhPayRecordMapper;
import com.bike.mapper.HhWithdrawAgentMapper;
import com.bike.util.Constant;
import com.bike.util.PageData;
import com.bike.util.TimeManager;
import com.bike.util.TransFerUtil;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.github.miemiedev.mybatis.paginator.domain.PageList;

@Service
public class HhWithdrawAgentServiceImpl extends BaseServcieImpl  {

	@Autowired
	HhWithdrawAgentMapper hhWithdrawAgentMapper;
	@Autowired
	HhAgentMapper hhAgentMapper;
	@Autowired
	HhPayRecordMapper hhPayRecordMapper;
	@Autowired
	HhAgentServiceImpl hhAgentServiceImpl;
	@Autowired
	HhPayRecordServiceImpl hhPayRecordServiceImpl;
	
	/**
	* 保存
	*/
	public void saveOrUpdate(PageData pd, HhWithdrawAgent record) {
		if(pd.getLong("withdrawAgentId")>0){
			 //编辑
			hhWithdrawAgentMapper.updateByPrimaryKeySelective(record);
		}else{
			hhWithdrawAgentMapper.insertSelective(record);
		}
	}
	
	/**
	* 删除
	*/
	public int deleteHhWithdrawAgentById(long withdrawAgentId) {
		return hhWithdrawAgentMapper.deleteByPrimaryKey(withdrawAgentId);
	}
	
	/**
	*列表分页
	*/
	public PageData selectHhWithdrawAgentList(PageData pd) {
		PageData result=new PageData();
		PageBounds pageBounds=(PageBounds) pd.get("pageB");
		String advanceFilter=pd.getString("advanceFilter");
		if(advanceFilter!=null&&!advanceFilter.equals("")){
			advanceFilter=advanceFilter.replaceAll("'", "");
			JSONArray array=JSONObject.parseArray(advanceFilter);
			StringBuffer buffer=new StringBuffer();
			for(int i=0;i<array.size();i++){
				JSONObject object=array.getJSONObject(i);
				String field=object.getString("field");
				String op=object.getString("op");//equal  contains  notequal  greater  greaterorequal  less  lessorequal  beginwith  endwith
				String value=object.getString("value");
				buffer.append(" and ").append(TransFerUtil.getMybatisField(field)).append(TransFerUtil.getMybatisOperation(op,value));
			}
			if(array.size()>0){
				pd.put("condition", buffer.toString());
			}
		}
		List<HhWithdrawAgent> records= hhWithdrawAgentMapper.selectByPage(pd,pageBounds);
		result.put("rows",records );
		result.put("total", ((PageList<HhWithdrawAgent>) records).getPaginator().getTotalCount());
		return result;
	}
	 
	/**
	*列表(全部)
	*/
	public List<HhWithdrawAgent> listAll(PageData pd) {
		return  hhWithdrawAgentMapper.selectAll(pd);
	}
	
	/**
	* 通过id获取数据
	*/
	public HhWithdrawAgent selectByHhWithdrawAgentId(Long withdrawAgentId) {
		return hhWithdrawAgentMapper.selectByPrimaryKey(withdrawAgentId);
	}

	public void updateWithdraw(PageData pd, HhWithdrawAgent hhWithdraw) {
		hhWithdraw.setStatus(1);
		hhWithdrawAgentMapper.updateWithdraw(hhWithdraw);
	}

	public PageData updateAgentWithdraw(HhAgent agent) {
		 
		 BigDecimal serviceFee=null;
		BigDecimal businessUserBalance=agent.getBalance();
		BigDecimal trueAccount=agent.getBalance();
		
		serviceFee=businessUserBalance.multiply(new BigDecimal(Constant.WXwithdrawFee)).setScale(2, RoundingMode.HALF_UP);
		if(serviceFee.doubleValue()==0){
			serviceFee=new BigDecimal("0.01");
		}
		trueAccount=businessUserBalance.subtract(serviceFee).subtract(new BigDecimal("2"));
		if(trueAccount.doubleValue()<0){
			return new PageData();
		}
		//余额清零
		agent.setBalance(new BigDecimal("0"));
		hhAgentMapper.updateByPrimaryKeySelective(agent);
		
		int time=TimeManager.currentTime();
		//增加提现记录
		HhWithdrawAgent hhWithdraw=new HhWithdrawAgent();
		
		hhWithdraw.setAgentId(agent.getAgentId());
		hhWithdraw.setAgentName(agent.getName());
		hhWithdraw.setAddTime(time);
		hhWithdraw.setAmount(trueAccount);
		hhWithdraw.setBank(agent.getBank());
		hhWithdraw.setBankBranch(agent.getBankBranch());
		hhWithdraw.setBankCode(agent.getBankCard());
		hhWithdraw.setBankUser(agent.getBankName());
		hhWithdraw.setPoundage(new BigDecimal("2"));
		hhWithdraw.setServiceAmount(serviceFee);
		hhWithdraw.setWithdrawAmount(businessUserBalance);
		hhWithdraw.setType(2);
		hhWithdrawAgentMapper.insertSelective(hhWithdraw);
		
		HhAgent platformagent= hhAgentServiceImpl.insertOrSelectByPrimaryKey();
		//提现金额
		 //交易记录
		 HhPayRecord payRecord=new HhPayRecord();
		 payRecord.setAddTime(TimeManager.currentTime());
		 payRecord.setMoney(trueAccount);
		 payRecord.setWithdrawId(hhWithdraw.getWithdrawAgentId());
		 payRecord.setUserId(agent.getAgentId());
		 payRecord.setUserName(agent.getName());
		 payRecord.setToUserId(platformagent.getAgentId());
		 payRecord.setToUserName(platformagent.getName());
		 payRecord.setTransType(Constant.withdraw);
		 payRecord.setStatus(0);
		 payRecord.setNotes(Constant.withdrawRecord);
		 payRecord.setType(Constant.agentType);
		 hhPayRecordMapper.insertSelective(payRecord);
		
		 hhPayRecordServiceImpl.insertAgentPayRecord(platformagent, trueAccount, Constant.platform, "代理商提现金额",true);
		//提现手续费
		 if(serviceFee!=null){
			 HhPayRecord payRecordSer=new HhPayRecord();
			 payRecordSer.setAddTime(TimeManager.currentTime());
			 payRecordSer.setMoney(serviceFee);
			 payRecordSer.setWithdrawId(hhWithdraw.getWithdrawAgentId());
			 payRecordSer.setUserId(agent.getAgentId());
			 payRecordSer.setUserName(agent.getName());
			 payRecordSer.setToUserId(platformagent.getAgentId());
			 payRecordSer.setToUserName(platformagent.getName());
			 payRecordSer.setTransType(Constant.withdrawService);
			 payRecordSer.setType(Constant.agentType);
			 payRecordSer.setNotes(Constant.withdrawServiceFee);
			 hhPayRecordMapper.insertSelective(payRecordSer);
			 hhPayRecordServiceImpl.insertAgentPayRecord(platformagent, serviceFee, Constant.platform, "代理商提现手续费",true);
		 }
		//银联转账手续费
		 HhPayRecord payRecordSer=new HhPayRecord();
		 payRecordSer.setAddTime(TimeManager.currentTime());
		 payRecordSer.setMoney(new BigDecimal("2"));
		 payRecordSer.setWithdrawId(hhWithdraw.getWithdrawAgentId());
		 payRecordSer.setUserId(agent.getAgentId());
		 payRecordSer.setUserName(agent.getName());
		 payRecordSer.setToUserId(platformagent.getAgentId());
		 payRecordSer.setToUserName(platformagent.getName());
		 payRecordSer.setType(Constant.agentType);
		 payRecordSer.setTransType(Constant.withdrawBankFeeType);
		 payRecordSer.setNotes(Constant.withdrawBankFee);
		 hhPayRecordMapper.insertSelective(payRecordSer);
		 
		//更新系统平台代理商余额  加入，提现完成 在减掉
		platformagent.setBalance(platformagent.getBalance().add(businessUserBalance ));
		  hhAgentMapper.updateByPrimaryKeySelective(platformagent);
		  hhPayRecordServiceImpl.insertAgentPayRecord(platformagent, new BigDecimal("2"), Constant.platform, "代理商提现银联转账手续费",true);
		  return new PageData();
	}

	public void updateAgentWithdrawOK(long withdrawId) {
		 
		//改变提现状态
		HhWithdrawAgent hhWithdraw=hhWithdrawAgentMapper.selectByPrimaryKey(withdrawId);
		hhWithdraw.setStatus(1);
		int result=hhWithdrawAgentMapper.updateWithdraw(hhWithdraw);
		if(result<=0){
			throw new RuntimeException("提现失败");
		}
		 
		int time=TimeManager.currentTime();
		//增加消费记录
		//系统平台代理
		HhAgent agent= hhAgentServiceImpl.insertOrSelectByPrimaryKey();
				
		//提现完成后 把代理商  进行中的提现记录  服务费提现记录  标记为完成
		PageData busRecordPd=new PageData();
//		if(hhWithdraw.getType()==2){
			hhPayRecordMapper.updateAgentWithdrawToSuccess(hhWithdraw);
//		} 
		
		 //更新系统平台代理商余额
		 agent.setBalance(agent.getBalance().subtract(hhWithdraw.getAmount()));
		 hhAgentMapper.updateByPrimaryKeySelective(agent);
		 hhPayRecordServiceImpl.insertAgentPayRecord(agent, hhWithdraw.getAmount(), Constant.platform, "代理商提现完成提现金额",false);
	}

}

